package cn.jy.nvr.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;



public class  ConvertCopyUtils {
	static Logger logger=Logger.getLogger(ConvertCopyUtils.class);
	public  static void ConvertFileToMP4(String hkFile,String mp4file) {
		logger.info("--进入转码--"+mp4file);
		try {
			File file=new File(hkFile);
			if(!file.exists()||file.length()<=0){
				return;
			}
			java.lang.StringBuffer cmd = new java.lang.StringBuffer();
			File ffmpegFile = new File("D://", "ffmpeg");
			ffmpegFile = new File(ffmpegFile, "bin");
			ffmpegFile = new File(ffmpegFile, "ffmpeg.exe");
			cmd.append(ffmpegFile.getAbsolutePath());
			cmd.append(" -threads 4  -i \"");
			cmd.append(hkFile);
			//ffmpeg -i test.mp4 -vcodec copy -f mp4 test1.mp4  -r 29.97 -vcodec libx264 -s 480x272 -flags +loop -cmp +chroma -crf 24 -bt 256k -refs 1 -coder 0 -subq 5 -partitions +parti4x4+parti8x8+partp8x8 -g 250 -keyint_min 25 -level 30 -qmin 10 -qmax 51 -trellis 2 -sc_threshold 40 -i_qfactor 0.71 -ab 128k -ar 48000 -ac 2 
			cmd.append("\" -vcodec  copy -f mp4  \"");
			cmd.append(mp4file);
			cmd.append("\"");
			System.out.println(cmd.toString());
			Process process = Runtime.getRuntime().exec(cmd.toString());
			
			try {
				{
					final InputStream is = process.getInputStream();
					new Thread(new Runnable() {

						public void run() {
							try {
								byte[] buf = new byte[1024];
								while (is.read(buf) != -1) {
								}
							} catch (Exception e) {
								e.printStackTrace();
							}finally{
								try {
									is.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
					}).start();
				}
				{
					final InputStream is = process.getErrorStream();
					new Thread(new Runnable() {

						public void run() {
							try {
								byte[] buf = new byte[1024];
								while (is.read(buf) != -1) {
								}
							} catch (Exception e) {
								e.printStackTrace();
							}finally{
								try {
									is.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
					}).start();
				}
				int waitFor = process.waitFor();
				logger.info("--转码完成--"+mp4file);
			} finally {
				process.destroy();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void deleteFile(String hkFile, String mp4File) {
      File hkfile=new File(hkFile);
      File mp4file=new File(mp4File);
      if(mp4file.exists()){
        hkfile.delete();  	  
      }
	}
}
